package com.hzc.springchan.config.exception;

import com.hzc.springchan.bean.exception.CException;
import com.hzc.springchan.bean.response.Response;
import com.hzc.springchan.enums.PubError;
import com.hzc.springchan.util.JSONUtils;
import com.hzc.springchan.util.LogUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常拦截配置类
 * @author chen990627
 * @date 2022/10/14
 */
@ControllerAdvice  //全局数据处理
public class ExceptionAdvice {

    @ExceptionHandler(CException.class)
    @ResponseBody
    public Response systemExceptionHandler(CException exception) {

        LogUtils.error("系统自定义异常拦截：{}", exception.toString());
        Response response = Response.newFailure(exception.getPubCode(), exception.getPubDesc(), exception.getPrivCode());
        response.setErrorDesc(exception.getPubDesc());
        LogUtils.inter("response: CEXCEPTION -> {}", JSONUtils.toJSON(response));
        return response;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object exceptionHandler(Exception exception) {

        LogUtils.error("系统异常拦截: 异常描述 -> {}, 异常位置 -> {}", exception.toString(), exception.getStackTrace()[0]);
        Response response = Response.newFailure(PubError.RUNTIME_EXCEPTION);
        LogUtils.inter("response: EXCEPTION -> {}", JSONUtils.toJSON(response));
        return response;
    }
}
